<template>
  <div>
    <!-- 搜索栏 ： 两个搜索框  搜索按钮  添加商家按钮  批量删除   -->
	<el-row>
	  <el-col :span="2"></el-col>
	  <el-col :span="3">
		   <el-input placeholder="请输入用户名搜索" v-model="query.contactName"/>
	  </el-col>
	  <el-col :span="3">
		   <el-input placeholder="请输入电话搜索" v-model="query.contactTel"/>
	  </el-col>
	  <el-col :span="3">
		   <el-input placeholder="请输入地址搜索" v-model="query.address"/>
	  </el-col>
	  <el-col :span="2">
	  	<el-button type="primary" plain @click="getByPage">搜索</el-button>
	  </el-col>
	  <el-col :span="5">
	  </el-col>
	  <el-col :span="1.5">
		  <el-button type="success" plain @click="showDialog">新增地址</el-button>
	  </el-col>
	  <el-col :span="1.5">
	  	  <el-button type="danger" plain @click="handleBatchDel">批量删除</el-button>
	  </el-col>
	  
	</el-row>
	
	
	<!-- 表格 -->
	<el-row class="table">
	  <el-col :span="2"></el-col>
	  <el-col :span="20">
		<el-table :data="pb.data" 
		          stripe 
				  border
				  @selection-change="handleSelectionChange">
		  <el-table-column type="selection"  width="55" />
		  <el-table-column prop="contactName" label="收货人姓名"/>
		  <el-table-column label="联系人性别">
			<template #default="scope">
				{{ scope.row.contactGender==0?'男':'女' }}
			</template>
		  </el-table-column>
		  <el-table-column prop="contactTel" label="联系人电话" />
		  <el-table-column prop="address" label="送货地址" show-overflow-tooltip/>
		  <el-table-column prop="userId" label="所属用户编号" />
		  <el-table-column label="操作" width="200px">
		        <template #default="scope">
		          <el-button size="small" @click="handleEdit(scope.row.addressId)">
		            编辑
		          </el-button>
		          <el-button
		            size="small"
		            type="danger"
		            @click="handleDelete(scope.row.addressId)"
		          >
		            删除
		          </el-button>
		        </template>
		      </el-table-column>
		</el-table>
		  
	  </el-col>
	  
	</el-row>  
	<!-- 分页组件 -->
	<el-row>
	  <el-col :span="6"></el-col>
	  <el-col :span="12">
		   <el-pagination
		        v-model:current-page="query.pageNow"
		        v-model:page-size="query.pageCount"
		        :page-sizes="[5, 8, 10, 20]"
		        layout="total, sizes, prev, pager, next, jumper"
		        :total="pb.totalRows"
		        @size-change="getByPage"
		        @current-change="getByPage"
		      />
	  </el-col>
	  
	</el-row>  
	
	<!-- 编辑地址信息的对话框  用于添加和修改 -->
	<el-dialog v-model="dialogFormVisible" title="编辑地址信息" width="500">
		<el-form :model="form">
		  <el-form-item label="收货人姓名" :label-width="formLabelWidth">
			<el-input v-model.trim="form.contactName" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="联系人性别" :label-width="formLabelWidth">
			<el-select v-model.number="form.contactGender" placeholder="选择性别" style="width: 140px">
				<el-option
					v-for="contactGender in contactGenderOptions"
					:key="contactGender.id"
					:label="contactGender.value"
					:value="contactGender.id"
				/>
			</el-select>
		  </el-form-item>
		  <el-form-item label="联系人电话" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.contactTel" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="送货地址" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.address" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="所属用户编号" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.userId" autocomplete="off" />
		  </el-form-item>
		</el-form>
		<template #footer>
		  <div class="dialog-footer">
			<el-button @click="dialogFormVisible = false">取消</el-button>
			<el-button type="primary" @click="addOrUpdate">
			  确认提交
			</el-button>
		  </div>
		</template>
  </el-dialog>
	
  </div>
</template>

<script setup>	
import { getCurrentInstance, onMounted, ref} from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';

//性别选项
let contactGenderOptions = ref([{id: null,value: '请选择'},{id: 0,value: '男'},{id: 1,value: '女'}])

	//获取配置的axios信息
	let {proxy} = getCurrentInstance();

  //对话框是否显示
  let dialogFormVisible = ref(false);
  let formLabelWidth = ref('100px');
  

  //表单数据 添加和修改
  let form = ref({
	  contactName: '',
	  contactGender: 0,
	  contactTel: '',
	  address: '',
	  userId: ''
  })
  
  //点新增商家信息按钮弹出对话框
  const showDialog = ()=>{
	  dialogFormVisible.value = true;
	  //数据清除
	  form.value = {
		  contactName: '',
		  contactGender: 0,
		  contactTel: '',
		  address: '',
		  userId: ''
	  }
  }

  //分页+搜索条件
  let query = ref({
	  pageNow: 1,
	  pageCount: 5,
	  contactName: '',
	  contactTel:'',
	  address:''
  })
  
  //分页对象 totalRows  totalPages  data(集合)
  let pb = ref({
	  totalRows: 0,
	  totalPages: 0,
	  data: []
  })

  const getByPage = ()=>{
	  proxy.$axios({
		  method: 'post',
		  url: '/address/page',
		  data: query.value
	  }).then(res=>{
		  console.log(res);
		  let resultBean = res.data;
		  if(resultBean.code==200){
			let pageBean = resultBean.data; 
			pb.value = pageBean;// totalRows  totalPages  data(集合)
		  }
	  })
  }
  
  //添加或修改
  const addOrUpdate = ()=>{
	  proxy.$axios({
		  method: 'post',
		  url: '/address',
		  data: form.value
	  }).then(res=>{
		  let resultBean = res.data;
		  if(resultBean.code == 200){
			  getByPage();
			  dialogFormVisible.value = false;
			  ElMessage.success('保存地址信息成功')
		  }else{
			  ElMessage.error(resultBean.msg);
		  }
	  })
  }
  
  //处理数据回显
  const handleEdit = (addressId)=>{
	  console.log('回显：addressId----',addressId);
	  //根据id查询对应的实体数据
	  proxy.$axios({
		  method: 'get',
		  url: '/address/'+addressId
	  }).then(res=>{
		  let resultBean = res.data;
		  if(resultBean.code == 200){
			  form.value = resultBean.data;
			  dialogFormVisible.value = true;
		  }else{
			  ElMessage.error(resultBean.msg);
		  }
	  })
  }
  
  //处理删除
  const handleDelete = (addressId)=>{
	  console.log('删除：addressId----',addressId);
	  ElMessageBox.confirm(
	      '您确定要删除该地址信息吗？',
	      '删除提示',
	      {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning',
	      }
	    )
	      .then(() => {
			  //确定删除
			  proxy.$axios({
				  method: 'delete',
				  url: '/address/'+addressId
			  }).then(res=>{
				  let resultBean = res.data;
				  if(resultBean.code == 200){
					  ElMessage.success('删除成功');
					  getByPage();
				  }else{
					  ElMessage.error(resultBean.msg);
				  }
			  })
			  
	      })
	      .catch(() => {
	           ElMessage.info('取消删除');
	      })
  }

  /* 多选&批量删除 */
  //选中项的id集合
  let selectOptions = ref([]);
  //表格中多选框选中或取消时会触发  也就是选中项变化
  const handleSelectionChange = (newSelection)=>{
	  console.log('选中项改变',newSelection);
	  selectOptions.value = []; //清空
	  newSelection.forEach((selOp)=>{
		  console.log(selOp.addressId);
		  selectOptions.value.push(selOp.addressId);
	  });
  }
  //批量删除的函数
  const handleBatchDel = ()=>{
	  console.log(selectOptions.value);
	  if(selectOptions.value.length==0){
		  ElMessage.info('请选中至少一条记录之后再进行删除');  
		  return;
	  }
	  
	  ElMessageBox.confirm(
	      '您确定要删除选中的用户信息吗？',
	      '删除提示',
	      {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning',
	      }
	    )
	      .then(() => {

			console.log(selectOptions.value);
			console.log(typeof(selectOptions.value));
			console.log(JSON.stringify(selectOptions.value));

			let str = JSON.stringify(selectOptions.value);
			str = str.substring(1,str.length-1);
	  			  
	  			  //确定删除
				proxy.$axios({
					method: 'post',
					url: '/address/batch/'+str,
				}).then(res=>{
					let resultBean = res.data;
					if(resultBean.code == 200){
						ElMessage.success('删除成功');  
						getByPage();
					}else{
						ElMessage.error(resultBean.msg);
					}
				})
	  			
	  			  
	      })
	      .catch(() => {
	           ElMessage.info('取消删除');
	      })
  }
  
  onMounted(()=>{
	  getByPage();
  })


</script>

<style>
	.table{
		margin-top: 20px;
	}
</style>